#include "PieceMemPool.h"

PieceMem<1024> GPieceMem;

int log2(int v)
{
	int ret=0;
	while(v>0) 
	{
		v=v>>1;
		ret++;
	}
	return ret-1;
}

void PieceMemPool::Init(int Size)
{
	mSize=Size;
	mData = malloc(PoolSize);
	mHead = mData;
	mTotalElem = PoolSize/mSize;
	mUsedElem = 0;
	for(int i=0;i<mTotalElem;i++)
	{
		if(i<mTotalElem-1)
		{
			unsigned int* ptr = (unsigned int*)((char*)mData+i*mSize);
			*ptr = (unsigned int)((char*)mData+(i+1)*mSize);
		}
		else
		{
			unsigned int* ptr = (unsigned int*)((char*)mData+i*mSize);
			*ptr = (unsigned int)0;
		}
	}
}

void* PieceMemPool::Malloc()
{
	void* ret = mHead;
	mHead = (void*)(*(unsigned int*)mHead);
	mUsedElem++;
	return ret;
}

void PieceMemPool::Free(void* mem)
{
	 *(unsigned int*)mem = (unsigned int)mHead;
	 mHead = mem;
}


